package org.fuys.coder.domain.auth.service.common.login.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import org.fuys.coder.common.entity.Pair;
import org.fuys.coder.common.util.EncryptUtil;
import org.fuys.coder.domain.auth.model.req.LoginReq;
import org.fuys.coder.domain.auth.model.res.AuthFailedEnum;
import org.fuys.coder.domain.auth.model.vo.UserVo;
import org.fuys.coder.domain.auth.repository.ICommonRepository;
import org.fuys.coder.domain.auth.service.common.login.ICommonLoginRepoService;
import org.fuys.coder.domain.file.service.AliYunOSSService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.domain.auth.service.common.login.impl
 * @className: CommonRepoServiceImpl
 * @author: WangJing
 * @description: 服务实现
 * @date: 2024/8/10 11:15
 * @version: 1.0
 */
@Service
public class CommonRepoServiceImpl implements ICommonLoginRepoService {
    @Resource
    private ICommonRepository commonRepository;

    @Resource
    private EncryptUtil encryptUtil;

    @Resource
    private AliYunOSSService aliYunOSSService;
    @Override
    public Pair<Integer, UserVo> login(LoginReq req) {
        //todo 思考再三 决定还是设置一个循环时长为一天的定时任务 来决定哪些用户需要被缓存到redis中
        //或者更按需要一些 当一个userId访问的次数达到每分钟超过1000次 可以考虑存放到redis中

        //这里只需要在登录时 根据用户名查出userid即可 至于JWT 那是应用层要关心的

        final UserVo userVo = commonRepository.selectUser(req);
        //不存在此用户 说明邮箱未被注册 或者是输入错误 提示邮箱不存在
        if(ObjectUtils.isEmpty(userVo)){
            return new Pair<Integer,UserVo>(AuthFailedEnum.LOGIN_EMAIL_NOT_EXIST.getIndex(), null);
        }
        //说明密码不匹配 返回对应信息
        if (!encryptUtil.verifyPassword(req.getPassword(), userVo.getPassword())) {
            return new Pair<>(AuthFailedEnum.LOGIN_PASSWORD_MISMATCH.getIndex(), null);
        }
        userVo.setAvatar(aliYunOSSService.buildUrl(Long.valueOf(userVo.getAvatar())));
        return new Pair<Integer, UserVo>(-1,userVo);
    }
}
